<?php
namespace app\admin\controller;

use ParseCsv\Csv;
use think\Db;
use think\facade\Config;

class Download extends Base{
    protected $needLogin = false;
    /**
     * 导出数据
     * @param string $table
     * @param string $title
     * @param array $where
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function export($table='',$title='',$where=[]){
        if(!$table){
           return $this->__e('请填写导出模型');
        }
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $header = [];
        $fields ='';
        $data = request()->param();
        $_table = strtolower(Config::get('database.prefix').$table);
        $database = Config::get('database.database');
        $model = Db::table($_table);
        $result = $model->where($where)->count();
        if(request()->isAjax()){
            if(!$result){
                return $this->__e('没有符合条件的数据');
            }else{
                $fields = urlencode($fields);
                $url = $_SERVER['REQUEST_URI']."&table={$table}&query={$fields}";
                return $this->__s('查询成功,可导出'.$result.'条数据',['url'=>$url]);
            }
        }
        $table_sql = "select * from information_schema.TABLES where TABLE_SCHEMA='{$database}' and TABLE_NAME='{$_table}'";
        $sql = "SELECT column_name,column_comment,data_type FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='{$database}' and TABLE_NAME = '{$_table}'";
        $_fields = Db::query($sql);
        $_table = Db::query($table_sql);
        $title = $_table[0]['TABLE_COMMENT'];

        if(isset($data['query']) && !empty($data['query'])){
            $fields = $data['query'];
            $header = explode(',',$data['query']);
        }else{
            if(isset($data['field']) && !empty($data['field'])){
                foreach ($data['field'] as $k=>$v){
                    $fields .= ','.$v;
                    array_push($header,$v);
                }
                $header = substr($fields,1);
            }else{
                foreach ($_fields as $v){
                    $fields .= ',' . $v['COLUMN_NAME'];
                    array_push($header,$v['COLUMN_COMMENT']);
                }
            }
            $fields = substr($fields,1);
        }
        $title = '下载'.$title .'_'.date('Ymd');
        $result = $model
            ->field($fields)
            ->where($where)
            ->select();
        $csv = new Csv();
        $csv->encoding('UTF-8','UTF-8');
        $csv->output("{$title}.csv", $result, $header);
        unset($result);
        ob_flush();
        flush();
    }
}